//
//  UserAccount.swift
//  WeiBo09
//
//  Created by 裘明 on 15/9/7.
//  Copyright © 2015年 qm. All rights reserved.
//

import UIKit

/// 用户帐户
/// - see: [http://open.weibo.com/wiki/OAuth2/access_token](http://open.weibo.com/wiki/OAuth2/access_token)
class UserAccount: NSObject, NSCoding {
    
    
    /// 用于调用access_token，接口获取授权后的access
    var access_token: String?
    /// access_token的生命周期，单位是秒数
    var expires_in: NSTimeInterval =  0 {
        didSet {
            expiresDate = NSDate(timeIntervalSinceNow: expires_in)
        }
    }
    /// 过期日期
    var expiresDate: NSDate?
    
    /// 当前授权用户的UID
    var uid: String?
    /// 友好名称
    var name: String?
    /// 头像
    var avatar_large: String?
    
    init(dict:[String: AnyObject]) {
        super.init()
        
        setValuesForKeysWithDictionary(dict)
    }
    
    override func setValue(value: AnyObject?, forUndefinedKey key: String) { }
    
    override var description: String {
        let keys = ["access_token", "expires_in", "expiresDate", "uid",  "name", "avatar_large"]
        
        // KVC的序列化
        return dictionaryWithValuesForKeys(keys).description
    }
    
    /// 获取沙盒路径
    static let accountpath = (NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).last! as NSString).stringByAppendingPathComponent("account.plist")
    
    /// 将当前对象归档保存
    func saveUserAccount() {
        // 键值归档
        NSKeyedArchiver.archiveRootObject(self, toFile: UserAccount.accountpath)
    }
    
    /// 加载用户信息，如果用户没有登录则返回nil
    ///
    /// - returns: 返回用户帐户
    class func loadUserAccount() -> UserAccount? {
        // 解档的时候，需判断token的有效期
        let account = NSKeyedUnarchiver.unarchiveObjectWithFile(accountpath) as? UserAccount
        if let date = account?.expiresDate {
            // 有效期大于当前日期
            if date.compare(NSDate()) == NSComparisonResult.OrderedDescending {
                
                return account
            }
        }
        return nil
    }
    
    // MARK: - NSCoding 为了避免每次都从网络加载属性，就使用归档去保存
    // 归档
    func encodeWithCoder(aCoder: NSCoder) {
        aCoder.encodeObject(access_token, forKey: "access_token")
        aCoder.encodeObject(expiresDate, forKey: "expiresDate")
        aCoder.encodeObject(uid, forKey: "uid")
        aCoder.encodeObject(name, forKey: "name")
        aCoder.encodeObject(avatar_large, forKey:"avatar_large")
        
    }
    
    // 解档，记得给属性赋值
    required init?(coder aDecoder: NSCoder) {
        access_token = aDecoder.decodeObjectForKey("access_token") as? String
        expiresDate =  aDecoder.decodeObjectForKey("expiresDate") as? NSDate
        uid = aDecoder.decodeObjectForKey("uid") as? String
        name =  aDecoder.decodeObjectForKey("name") as? String
        avatar_large = aDecoder.decodeObjectForKey("avatar_large") as? String
    }
    
}
